import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class ReflectTest {
    public static void reflectNewInstance() {
        Class<?> c1 = null;
        try {
            c1 = Class.forName("Student");
            Student student = (Student) c1.newInstance();
        } catch (ClassNotFoundException
                 | InstantiationException
                 | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    public static void reflectPrivateConstructor() {
        Class<Student> c1 = null;
        try {
            c1 = (Class<Student>)Class.forName("Student");
            Constructor<Student> constructor = c1.getDeclaredConstructor(String.class,int.class);
            constructor.setAccessible(true);
            Student student = constructor.newInstance("佩奇",10);
            System.out.println(student);
        }catch (ClassNotFoundException
                | NoSuchMethodException
                | InvocationTargetException
                | InstantiationException
                | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    public static void reflectPrivateField() {
        Class<Student> c1 = null;
        try {
            c1 = (Class<Student>)Class.forName("Student");
            Field field = c1.getDeclaredField("name");
            field.setAccessible(true);
            Student student = c1.newInstance();
            field.set(student,"沸羊羊");
            System.out.println(student);
        }catch (ClassNotFoundException
                | NoSuchFieldException
                | InstantiationException
                | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //reflectNewInstance();
        //reflectPrivateConstructor();
        reflectPrivateField();
    }
}
